﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Forms;
using RiskMan.DataClass.Models;
using System.IO;
using System.Collections.ObjectModel;
using TheControllerRisk.Settings;
using RiskMan.Views.Dialogs;

namespace RiskMan.Config
{
    /// <summary>
    /// Логика взаимодействия для newQuikView.xaml
    /// </summary>
    public partial class newQuikView : Window
    {
        #region Обновление всех визуальных данных

        private void Refresh ( )
        {
            AllAccounts.Clear( );
            var  list = data.GetTradeAllList( );
            for ( int i = 0; i < list.Count; i++ )
                AllAccounts.Add( list[i] );

            Accounts.Clear( );

            Update( );
        }

        private void Update ( )
        {
            ObservableCollection<String> result = new ObservableCollection<String>( );
            for ( int i = 0; i < Accounts.Count; i++ )
            {
                result.Add( Accounts [ i ].ClientCode + " => " + Accounts [ i ].Account );
            }
            ListBox_Accounts.ItemsSource = result;

            result = new ObservableCollection<String>( );
            foreach ( var tmp in AllAccounts )
            {
                result.Add( tmp.ClientCode + " => " + tmp.Account );
            }
            ListBox_AllAccounts.ItemsSource = result;
        }

        #endregion 

        private DataClass.Data data;
        private QuikItem quikItem = new QuikItem();
        public QuikItem tmpQuik = new QuikItem();
        bool tr = false;

        ObservableCollection<Trade> AllAccounts = new ObservableCollection<Trade>( );
        ObservableCollection<Trade> Accounts = new ObservableCollection<Trade>( );

        public newQuikView ( bool tr, QuikItem quik, DataClass.Data data )
        {
            InitializeComponent( );

            this.tr = tr;
            this.data = data;
            this.quikItem = quik;
            this.tmpQuik = ( QuikItem ) cfg.DeepClone( quik );

            TextBox_Name.Text = quikItem.Name;
            TextBox_PathQuik.Text = quikItem.Path;

            Accounts = quikItem.TradeList;
            var list = data.GetTradeAllList( );
            for ( int i = 0; i < list.Count; i++ )
            {
                bool tru = false;
                foreach ( var tmp in Accounts )
                {
                    if ( tmp.ClientCode == list [ i ].ClientCode )
                        tru = true;
                }
                if ( tru == false )
                    AllAccounts.Add( list [ i ] );
            }
            Update( );
        }

        #region Кнопка "Отмена"

        private void button7_Click(object sender, RoutedEventArgs e)
        {
            tmpQuik = null;
            Close();
        }

        #endregion

        #region Добавление счета в список счетов текущего квика
        
        private void Button_AddOne_Click(object sender, RoutedEventArgs e)
        {
            add( );   
        }
        private void ListBox_AllAccounts_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            add( );    
        }

        void add ( )
        {
            if ( ListBox_AllAccounts.SelectedItems.Count == 1 )
            {
                int selectIndex = ListBox_AllAccounts.SelectedIndex;
                Accounts.Add( AllAccounts [ selectIndex ] );
                AllAccounts.RemoveAt( selectIndex );
            }
            Update( );
        }

        #endregion

        #region  Удаление счета из списка счетов текущего квика

        private void ListBox_Accounts_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            dell( );
        }
        private void Button_DellOne_Click(object sender, RoutedEventArgs e)
        {
            dell( );
        }

        void dell ( )
        {
            if ( ListBox_Accounts.SelectedItems.Count == 1 )
            {
                int selectIndex = ListBox_Accounts.SelectedIndex;
                AllAccounts.Add( Accounts [ selectIndex ] );
                Accounts.RemoveAt( selectIndex );
            }
            Update( );
        }
        #endregion

        #region Добавление всех счетов в список счетов текущего квика

        private void Button_AddAll_Click ( object sender, RoutedEventArgs e )
        {
            foreach ( var tmp in AllAccounts )
            {
                Accounts.Add( tmp );
            }
            AllAccounts.Clear( );
            Update( );
        }

        #endregion

        #region Удаление всех счетов из списка счетов текущего квика

        private void Button_DellAll_Click(object sender, RoutedEventArgs e)
        {
            foreach ( var tmp in Accounts )
            {
                AllAccounts.Add( tmp );
            }
            Accounts.Clear( );
            Update();
        }

        #endregion

        #region Перезапуск дде вывода данных из квика

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            QuikIntegration.dde.QuikUtil.StartDDE();
            Refresh();
        }

        #endregion

        #region Кнопка "Применить"
        
        private void Button_Accept_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (TextBox_Name.Text.Trim() != "")
                    quikItem.Name = TextBox_Name.Text;
                else
                {
                    new DialogOkCancel("Введите имя", "Ошибка");
                    return;
                }
                if (TextBox_PathQuik.Text.Trim() != "")
                    quikItem.Path = TextBox_PathQuik.Text;
                else
                {
                    new DialogOkCancel( "Введите путь", "Ошибка" );
                    return;
                }

                if (tr == false)
                {
                    foreach (var tmp in data.T2QItems)
                        if (quikItem.Name == tmp.Name)
                        {
                            new DialogOkCancel( "Измените имя. Такое имя  уже есть", "Ошибка" );
                            return;
                        }
                }
                string text = "";
                foreach (var tmp in quikItem.TradeList)
                    text += tmp.ClientCode + "; ";
                quikItem.Comments = text;

                tmpQuik = quikItem;
                this.Close();
            }
            catch (Exception ex)
            {
                new DialogOkCancel( "Добавление нового терминала закончилось ошибкой: " + ex.ToString( ), "Ошибка" );
            }
        }

        #endregion

        #region Выбор пути до квик терминала

        private void Button_Path_Click(object sender, RoutedEventArgs e)
        {
            FolderBrowserDialog tmp = new FolderBrowserDialog();
            if (tmp.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                TextBox_PathQuik.Text = tmp.SelectedPath;
                quikItem.Path = tmp.SelectedPath;
            }
        }

        #endregion

        private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            TextBox_PathQuik.Text = ( sender as System.Windows.Controls.ComboBox ).SelectedItem.ToString( );
            quikItem.Path = (sender as System.Windows.Controls.ComboBox).SelectedItem.ToString();
        }

        private void Window_Loaded ( object sender, RoutedEventArgs e )
        {

        }

        private void ListBox_AllAccounts_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }
            
    }
}
